package com.relatev.minecraft.TRMobAPI;

import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TRAbilityJsonSolver implements JsonDeserializer<TRAbility>, JsonSerializer<TRAbility> {

    private static Gson gson = new Gson();

    @Override
    public TRAbility deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
        JsonObject jo = je.getAsJsonObject();
        String id = jo.get("ID").getAsString();
        try {
            TRAbility tra = (TRAbility) gson.fromJson(jo, Class.forName(id));
            return tra;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(TRAbilityJsonSolver.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public JsonElement serialize(TRAbility ab, Type type, JsonSerializationContext jsc) {
        JsonObject jo = new JsonObject();
        for (Field field : ReflectionUtils.getDeclaredFieldsIncludingParents(ab.getClass())) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(TRFieldConfigurable.class)) {
                try {
                    jo.add(field.getName(), gson.toJsonTree(field.get(ab)));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    Logger.getLogger(TRMobJsonSerializer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return jo;
    }
}
